<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>在线考试终端</title>
    <link rel="stylesheet" href="../css/all.min.css">
    <style>
        @font-face {
            font-family: 'MyCustomFont';
            src: url('../font/MyFont-pen.ttf') format('woff2'),
                 url('../font/MyFont-pen.ttf') format('woff'),
                 url('../font/MyFont-pen.ttf') format('truetype');
            font-weight: normal;
            font-style: normal;
        }
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            margin: 0;
            padding: 20px;
            background-color: #fff;
            color: #333;
        }
        .container {
            max-width: 1000px;
            margin: 0 auto;
            background-color: #fff;
            padding: 30px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            border-radius: 5px;
            position: relative;
        }
        .header {
            text-align: center;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 1px solid #eee;
            position: relative;
        }
        .header h1 {
            color: #2c3e50;
            margin-bottom: 5px;
        }
        .header h2 {
            color: #7f8c8d;
            font-size: 18px;
            margin-top: 0;
        }
        .exam-info {
            font-size: 14px;
            color: #7f8c8d;
            margin-bottom: 10px;
            display: flex;
            justify-content: center;
        }

        .exam-info div{
            margin: 10px;
        }
        .exam-details {
            display: flex;
            justify-content: space-between;
            margin: 20px;
            font-size: 14px;
        }
        .section {
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 1px dashed #ddd;
        }
        .section-title {
            color: #3498db;
            margin-bottom: 15px;
            padding-bottom: 5px;
            border-bottom: 2px solid #3498db;
        }
        .question {
            margin-bottom: 15px;
            padding: 10px;
            transition: all 0.3s ease;
        }
        .question-id {
            font-weight: bold;
        }
        .question-stem {
            margin-bottom: 10px;
            font-weight: bold;
        }
        .options {
            margin-left: 20px;
        }
        .option {
            margin-bottom: 5px;
            display: flex;
            align-items: center;
        }
        .answer-input {
            margin-right: 10px;
        }
        .text-answer {
            padding: 8px;
            border-bottom: 1px solid #000;
            border-top: 0px;
            border-right: 0px;
            border-left: 0px;
            font-size: 20px;
        }
        .reference {
            display: none !important;
            margin-top: 10px;
            padding: 10px;
            background-color: #e8f4fc;
            border-left: 4px solid #3498db;
            font-size: 14px;
        }
        .btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 10px 15px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 16px;
            margin: 10px 5px;
            cursor: pointer;
            border-radius: 4px;
            transition: all 0.3s;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        .btn-check {
            background: linear-gradient(135deg, #3498db 0%, #8998db 100%);
        }
        .btn-check:hover {
            background: linear-gradient(135deg, #8998db 0%, #3498db 100%);
        }
        .btn-reset {
            background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
        }
        .btn-reset:hover {
            background: linear-gradient(135deg, #c0392b 0%, #e74c3c 100%);
        }
        .btn-print {
            background: linear-gradient(135deg, #9b59b6 0%, #8e44ad 100%);
        }
        .btn-print:hover {
            background: linear-gradient(135deg, #8e44ad 0%, #9b59b6 100%);
        }
        .file-input {
            margin: 20px 0;
            text-align: center;
        }
        .hidden {
            display: none;
        }
        
        /* 固定在右侧的按钮面板 */
        .fixed-btn-panel {
            position: fixed;
            right: 20px;
            top: 50%;
            transform: translateY(-50%);
            background-color: white;
            padding: 15px;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            z-index: 1000;
            display: flex;
            flex-direction: column;
        }
        
        /* 文件加载区域样式 */
        .file-load-area {
            text-align: center;
            padding: 50px 20px;
            border: 2px dashed #ddd;
            border-radius: 5px;
            margin: 50px auto;
            max-width: 500px;
            background-color: #f9f9f9;
        }
        
        .file-load-area h2 {
            color: #3498db;
            margin-bottom: 20px;
        }
        
        #jsonFile {
            display: none;
        }
        
        .file-upload-btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            display: inline-block;
            margin-bottom: 15px;
        }
        
        .file-upload-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }

        /* 总分显示 */
        .total-score {
            font-family: 'MyCustomFont';
            background-image: url('../img/bg-score.png');
            background-size: cover; 
            background-position: center;
            background-repeat: no-repeat;
            position: absolute;
            font-size: 88px;
            top: 50px;
            right: 100px;
            color: #dc3620;
            font-weight: bold;
            display: none;
        }

        /* 打印样式 */
        @media print {
            .fixed-btn-panel, .file-load-area, .modal-container {
                display: none !important;
            }
            body {
                background-color: white;
                padding: 0;
            }
            .container {
                box-shadow: none;
                padding: 10px;
            }
            .reference {
                display: none !important;
            }
            .total-score {
                display: block !important;
            }

            .watermark {
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                z-index: 9999;
                pointer-events: none;
                opacity: 0.1;
                display: flex;
                justify-content: center;
                align-items: center;
                font-size: 48px;
                font-weight: bold;
                transform: rotate(-15deg);
                color: #000;
            }
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .fixed-btn-panel {
                position: static;
                transform: none;
                flex-direction: row;
                flex-wrap: wrap;
                justify-content: center;
                margin-top: 20px;
                box-shadow: none;
                background-color: transparent;
            }
            .fixed-btn-panel .btn {
                margin: 5px;
                padding: 8px 12px;
            }
            .header {
                padding-top: 40px;
            }
        }

        /* 模态框样式 */
        .modal-container {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 2000;
            opacity: 0;
            visibility: hidden;
            transition: opacity 0.3s ease, visibility 0.3s ease;
        }
        
        .modal-container.active {
            opacity: 1;
            visibility: visible;
        }
        
        .modal {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
            max-width: 350px;
            width: 90%;
            transform: scale(0.8);
            transition: transform 0.3s ease;
        }
        
        .modal-container.active .modal {
            transform: scale(1);
        }
        
        .modal-header {
            padding: 15px 20px;
            border-bottom: 1px solid #e9ecef;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .modal-title {
            font-size: 20px;
            font-weight: bold;
            color: #2c3e50;
        }
        
        .modal-close {
            font-size: 24px;
            color: #7f8c8d;
            cursor: pointer;
            transition: color 0.3s ease;
        }
        
        .modal-close:hover {
            color: #333;
        }
        
        .modal-content {
            padding: 20px;
            line-height: 1.6;
            color: #333;
        }
        
        .modal-footer {
            padding: 15px 20px;
            border-top: 1px solid #e9ecef;
            display: flex;
            justify-content: flex-end;
        }
        
        .modal-btn {
            margin-left: 10px;
            padding: 8px 15px;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 14px;
        }
        
        .modal-btn-primary {
            background-color: #3498db;
            color: white;
            border: 1px solid #3498db;
        }
        
        .modal-btn-primary:hover {
            background-color: #2980b9;
        }
        
        .modal-btn-secondary {
            background-color: white;
            color: #333;
            border: 1px solid #ddd;
        }
        
        .modal-btn-secondary:hover {
            background-color: #f8f9fa;
        }
        
        /* 正确和错误答案的样式 */
        .correct {
            background-color: #fff;
            border-radius: 4px;
        }
        
        .incorrect {
            background-color: #ffebee;
            border-radius: 4px;
        }

        .btn-auto {
            background: linear-gradient(135deg, #2ecc71 0%, #27ae60 100%);
        }
        .btn-auto:hover {
            background: linear-gradient(135deg, #27ae60 0%, #2ecc71 100%);
        }

         /* 密码输入模态框样式 */
        .password-input {
            width: 100%;
            padding: 8px;
            margin: 10px 0;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        
        .password-error {
            color: #e74c3c;
            margin-top: 5px;
            display: none;
        }

        #autoAnswerBtn::before,
        #autoAnswerBtn::after {
          content: '';
          position: absolute;
          top: 50%;
          width: calc(50% - 75px);
          border-top: 1px dashed #999;
        }
        #autoAnswerBtn::before {
          right: calc(50% + 75px);
        }
        #autoAnswerBtn::after {
          left: calc(50% + 75px);
        }
    </style>
</head>
<body>
    <!-- 水印容器 -->
    <div id="watermark" class="watermark"></div>

    <div class="container">
        <!-- 文件加载区域 -->
        <div class="file-load-area" id="fileLoadArea">
            <h2>请加载考试文件</h2>
            <label for="jsonFile" class="file-upload-btn">
                <i class="fas fa-file-upload"></i> 选择考试文件
            </label>
            <input type="file" id="jsonFile" accept=".json">
            <p>请选择JSON格式的考试文件</p>
        </div>

        <!-- 考试内容区域 - 默认隐藏 -->
        <div id="examContent" class="hidden">
            <div class="header">
                <h1 id="exam-title"></h1>
                <h2 id="exam-subtitle"></h2>
                <div class="exam-info">
                    <div>考试时间：120分钟</div>
                    <div>满分：100分</div>
                </div>

                <!-- 考试说明 -->
                <div class="exam-instructions" style="margin: 20px 0; padding: 15px; background-color: #f8f9fa; border-left: 4px solid #3498db; text-align: left;">
                    <h4 style="margin-top: 0; color: #2c3e50;">考试说明：</h4>
                    <ol style="padding-left: 20px; margin-bottom: 0;">
                        <li>考试开始前，由监考人员统一发放考试文件；</li>
                        <li>请仔细阅读各题目要求，按题型规范作答，避免漏答；</li>
                        <li>请在规定考试时间内完成答题并提交答卷，逾期系统将自动关闭提交功能；</li>
                        <li>答题结束后，点击 “提交答卷” 按钮，由监考人员输入密码完成交卷；</li>
                        <li>答卷提交后，需打印纸质版试卷，由考生本人在指定位置签字确认；</li>
                        <li>监考人员核对答卷信息无误后，在纸质试卷上签字确认，完成考试流程。</li>
                    </ol>
                </div>
                
                <div class="exam-details">
                    <div>姓名：<input type="text" class="text-answer" style="width: 150px;" id="studentName"></div>
                    <div>电话：<input type="text" class="text-answer" style="width: 150px;" id="studentPhone"></div>
                </div>
            </div>

            <!-- 总分显示 -->
            <div class="total-score" id="totalScoreDisplay"><span id="totalScoreValue">0</span></div>

            <!-- 单选题部分 -->
            <div class="section" id="singleChoiceSection">
                <h2 class="section-title" id="singleChoiceTitle"></h2>
                <div id="singleChoiceQuestions"></div>
            </div>

            <!-- 多选题部分 -->
            <div class="section" id="multipleChoiceSection">
                <h2 class="section-title" id="multipleChoiceTitle"></h2>
                <div id="multipleChoiceQuestions"></div>
            </div>

            <!-- 判断题部分 -->
            <div class="section" id="judgeSection">
                <h2 class="section-title" id="judgeTitle"></h2>
                <div id="judgeQuestions"></div>
            </div>
        </div>


        <!-- 签名区域 -->
        <div class="signature-area" style="border: 1px dashed #e0e0e0; border-radius: 8px;">
            <div style="display: flex; justify-content: space-between; align-items: center; width: 100%; margin: 0 auto;">
                <!-- 考试签名区 -->
                <div class="sign-section" style="flex: 1; padding: 20px; background-color: white; border-radius: 6px; box-shadow: 0 2px 4px rgba(0,0,0,0.05);">
                    <h4 style="color: #333; font-size: 16px; margin-bottom: 15px; border-bottom: 2px solid #ccc; padding-bottom: 5px;">考试签名：</h4>
                    <h4 style="color: #333; font-size: 16px; margin-bottom: 15px; border-bottom: 2px solid #ccc; padding-bottom: 5px;">考试时间：<font id="startTime" style="font-family: 'MyCustomFont';font-size: 20px;"></font></h4>
                </div>

                <!-- 监考签名区 -->
                <div class="sign-section" style="flex: 1; padding: 20px; background-color: white; border-radius: 6px; box-shadow: 0 2px 4px rgba(0,0,0,0.05);">
                    <h4 style="color: #333; font-size: 16px; margin-bottom: 15px; border-bottom: 2px solid #ccc; padding-bottom: 5px;">监考签名：</h4>
                    <h4 style="color: #333; font-size: 16px; margin-bottom: 15px; border-bottom: 2px solid #ccc; padding-bottom: 5px;">交卷时间：<font id="submitTime" style="font-family: 'MyCustomFont';font-size: 20px;"></font></h4>
                </div>
            </div>
        </div>


        <!-- 考试说明 -->
        <div class="exam-instructions" style="margin: 20px 0; padding: 15px; background-color: #f8f9fa; border-left: 4px solid #3498db; text-align: left;">
            <h4 style="margin-top: 0; color: #2c3e50;">注意：</h4>
            <ol style="padding-left: 20px; margin-bottom: 0;">
                <li>环境要求：保持安静，不得喧哗或与他人交流；</li>
                <li>诚信应考：严格遵守纪律，禁止抄袭、替考、交流答案等作弊行为。</li>
            </ol>
        </div>

        <!-- 内部资料提示 -->
        <div id="autoAnswerBtn" style="text-align: center; margin: 30px auto 0; color: #999; font-size: 16px; padding-top: 10px; position: relative; max-width: 600px;">
          <span style="display: inline-block; position: relative; z-index: 1; background: white; padding: 0 15px;">内部资料丨请勿外传</span>
        </div>
    </div>

    <!-- 固定在右侧的按钮面板 -->
    <div class="fixed-btn-panel hidden" id="fixedBtnPanel">
        <button class="btn btn-check" id="checkBtn">
            <i class="fas fa-check-circle"></i> 提交答卷
        </button>
        <button class="btn btn-print" id="printBtn">
            <i class="fas fa-print"></i> 试卷打印
        </button>
        <button class="btn btn-reset" id="resetBtn">
            <i class="fas fa-redo"></i> 重置答案
        </button>
    </div>

    <!-- 模态框 -->
    <div class="modal-container" id="modal">
        <div class="modal">
            <div class="modal-header">
                <div class="modal-title" id="modalTitle">提示</div>
                <div class="modal-close" id="modalClose">&times;</div>
            </div>
            <div class="modal-content" id="modalContent"></div>
            <div class="modal-footer">
                <button class="modal-btn modal-btn-secondary" id="modalCancel">取消</button>
                <button class="modal-btn modal-btn-primary" id="modalConfirm">确认</button>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let examData = {};
        let isSubmitted = false;
        let currentModalCallback = null;
        // 存储MD5密码
        let examPassword = '';
        let startTime = ''; // 考试时间
        let submitTime = ''; // 交卷时间

        // DOM元素
        const jsonFileInput = document.getElementById('jsonFile');
        const fileLoadArea = document.getElementById('fileLoadArea');
        const examContent = document.getElementById('examContent');
        const examTitle = document.getElementById('exam-title');
        const examSubtitle = document.getElementById('exam-subtitle');
        const fixedBtnPanel = document.getElementById('fixedBtnPanel');
        const checkBtn = document.getElementById('checkBtn');
        const printBtn = document.getElementById('printBtn');
        const resetBtn = document.getElementById('resetBtn');
        const totalScoreDisplay = document.getElementById('totalScoreDisplay');
        const totalScoreValue = document.getElementById('totalScoreValue');
        
        // 模态框元素
        const modal = document.getElementById('modal');
        const modalTitle = document.getElementById('modalTitle');
        const modalContent = document.getElementById('modalContent');
        const modalClose = document.getElementById('modalClose');
        const modalConfirm = document.getElementById('modalConfirm');
        const modalCancel = document.getElementById('modalCancel');

        // 获取自动答题按钮
        const autoAnswerBtn = document.getElementById('autoAnswerBtn');

        // 自动选择正确答案
        autoAnswerBtn.addEventListener('click', function() {
            if (isSubmitted) {
                showModal('操作失败', '考试已提交，不能自动答题。', () => {});
                return;
            }
            
            showModal('自动答题', '确定要自动选择所有答案吗？', function() {
                // 自动选择单选题答案
                if (examData.singleChoice && examData.singleChoice.questions) {
                    examData.singleChoice.questions.forEach(question => {
                        const correctOption = document.querySelector(`input[name="single_${question.id}"][value="${question.answer}"]`);
                        if (correctOption) {
                            correctOption.checked = true;
                        }
                    });
                }
                
                // 自动选择多选题答案
                if (examData.multipleChoice && examData.multipleChoice.questions) {
                    examData.multipleChoice.questions.forEach(question => {
                        // 清除已选选项
                        document.querySelectorAll(`input[name="multiple_${question.id}"]`).forEach(input => {
                            input.checked = false;
                        });
                        
                        // 选择正确答案
                        question.answer.split('').forEach(answer => {
                            const correctOption = document.querySelector(`input[name="multiple_${question.id}"][value="${answer}"]`);
                            if (correctOption) {
                                correctOption.checked = true;
                            }
                        });
                    });
                }
                
                // 自动选择判断题答案
                if (examData.judge && examData.judge.questions) {
                    examData.judge.questions.forEach(question => {
                        const correctOption = document.querySelector(`input[name="judge_${question.id}"][value="${question.answer}"]`);
                        if (correctOption) {
                            correctOption.checked = true;
                        }
                    });
                }
                
                showModal('操作成功', '已自动选择所有正确答案。', () => {});
            });
        });

        // 点击文件上传按钮
        document.querySelector('.file-upload-btn').addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            jsonFileInput.click();
        });

        // 加载JSON文件
        jsonFileInput.addEventListener('change', function() {
            const file = jsonFileInput.files[0];
            if (!file) {
                return;
            }

            const reader = new FileReader();
            reader.onload = function(e) {
                try {
                    examData = JSON.parse(e.target.result);
                    // 检查考试配置中是否有密码
                    if (examData.password) {
                        examPassword = examData.password;
                    }

                    startTime = new Date();
                    updateExamTimeDisplay();

                    renderExam();
                    fileLoadArea.style.display = 'none';
                    examContent.classList.remove('hidden');
                    fixedBtnPanel.classList.remove('hidden');
                } catch (error) {
                    showModal('错误', `解析JSON文件失败: ${error.message}`, () => {});
                }
            };
            reader.readAsText(file);
        });

        // 考试时间显示
        function updateExamTimeDisplay() {
            const startTimeElement = document.getElementById('startTime');
            startTimeElement.textContent = `${formatDateTime(startTime)}`;
        }

        // 渲染考试内容
        function renderExam() {
            // 设置标题和副标题
            examTitle.textContent = examData.title || '';
            examSubtitle.textContent = examData.subtitle || '';

            // 渲染单选题
            renderSingleChoiceQuestions();
            
            // 渲染多选题
            renderMultipleChoiceQuestions();
            
            // 渲染判断题
            renderJudgeQuestions();
        }


        // 渲染单选题
        function renderSingleChoiceQuestions() {
            const section = document.getElementById('singleChoiceQuestions');
            section.innerHTML = '';
            
            if (!examData.singleChoice || !examData.singleChoice.questions) return;
            
            const title = document.getElementById('singleChoiceTitle');
            title.textContent = examData.singleChoice.title || '';
            
            // 解析标题中的每题分数
            const scorePerQuestion = extractScoreFromTitle(title.textContent) || 2;
            
            examData.singleChoice.questions.forEach(question => {
                const questionDiv = document.createElement('div');
                questionDiv.className = 'question';
                questionDiv.dataset.id = question.id;
                questionDiv.dataset.type = 'single';
                questionDiv.dataset.answer = question.answer;
                // 优先使用题目自定义分数，否则使用从标题解析的分数
                questionDiv.dataset.score = question.score !== undefined ? question.score : scorePerQuestion;
                
                let html = `
                    <div class="question-stem">
                        <span class="question-id">${question.id}.</span> ${question.stem}
                    </div>
                    <div class="options">
                `;
                
                question.options.forEach(option => {
                    const optionId = `single_${question.id}_${option.charAt(0)}`;
                    html += `
                        <div class="option">
                            <input type="radio" id="${optionId}" name="single_${question.id}" class="answer-input" value="${option.charAt(0)}">
                            <label for="${optionId}">${option}</label>
                        </div>
                    `;
                });
                
                html += `
                    </div>
                    <div class="reference hidden">${question.reference || '暂无解析'}</div>
                `;
                
                questionDiv.innerHTML = html;
                section.appendChild(questionDiv);
            });
        }

        // 渲染多选题
        function renderMultipleChoiceQuestions() {
            const section = document.getElementById('multipleChoiceQuestions');
            section.innerHTML = '';
            
            if (!examData.multipleChoice || !examData.multipleChoice.questions) return;
            
            const title = document.getElementById('multipleChoiceTitle');
            title.textContent = examData.multipleChoice.title || '';
            
            // 解析标题中的每题分数
            const scorePerQuestion = extractScoreFromTitle(title.textContent) || 1;
            
            examData.multipleChoice.questions.forEach(question => {
                const questionDiv = document.createElement('div');
                questionDiv.className = 'question';
                questionDiv.dataset.id = question.id;
                questionDiv.dataset.type = 'multiple';
                questionDiv.dataset.answer = question.answer;
                // 使用题目自定义分数或从标题解析的分数
                questionDiv.dataset.score = question.score !== undefined ? question.score : scorePerQuestion;
                
                let html = `
                    <div class="question-stem">
                        <span class="question-id">${question.id}.</span> ${question.stem}
                    </div>
                    <div class="options">
                `;
                
                question.options.forEach(option => {
                    const optionId = `multiple_${question.id}_${option.charAt(0)}`;
                    html += `
                        <div class="option">
                            <input type="checkbox" id="${optionId}" name="multiple_${question.id}" class="answer-input" value="${option.charAt(0)}">
                            <label for="${optionId}">${option}</label>
                        </div>
                    `;
                });
                
                html += `
                    </div>
                    <div class="reference hidden">${question.reference || '暂无解析'}</div>
                `;
                
                questionDiv.innerHTML = html;
                section.appendChild(questionDiv);
            });
        }

        // 渲染判断题
        function renderJudgeQuestions() {
            const section = document.getElementById('judgeQuestions');
            section.innerHTML = '';
            
            if (!examData.judge || !examData.judge.questions) return;
            
            const title = document.getElementById('judgeTitle');
            title.textContent = examData.judge.title || '';
            
            // 解析标题中的每题分数
            const scorePerQuestion = extractScoreFromTitle(title.textContent) || 1;
            
            examData.judge.questions.forEach(question => {
                const questionDiv = document.createElement('div');
                questionDiv.className = 'question';
                questionDiv.dataset.id = question.id;
                questionDiv.dataset.type = 'judge';
                questionDiv.dataset.answer = question.answer;
                // 使用题目自定义分数或从标题解析的分数
                questionDiv.dataset.score = question.score !== undefined ? question.score : scorePerQuestion;
                
                const trueId = `judge_${question.id}_true`;
                const falseId = `judge_${question.id}_false`;
                
                let html = `
                    <div class="question-stem">
                        <span class="question-id">${question.id}.</span> ${question.stem}
                    </div>
                    <div class="options">
                        <div class="option">
                            <input type="radio" id="${trueId}" name="judge_${question.id}" class="answer-input" value="√">
                            <label for="${trueId}">正确</label>
                        </div>
                        <div class="option">
                            <input type="radio" id="${falseId}" name="judge_${question.id}" class="answer-input" value="×">
                            <label for="${falseId}">错误</label>
                        </div>
                    </div>
                    <div class="reference hidden">${question.reference || '暂无解析'}</div>
                `;
                
                questionDiv.innerHTML = html;
                section.appendChild(questionDiv);
            });
        }

        // 从标题中提取每题分数
        function extractScoreFromTitle(title) {
            // 匹配更灵活的分数格式
            const regex = /(?:每题|每小题|每空|每问)?\s*(\d+)\s*分\/?\s*(?:题|空|问)?|每题?\s*(\d+)\s*分/;
            const match = title.match(regex);
            
            if (match) {
                // 返回第一个捕获到的数字
                return parseInt(match[1] || match[2]);
            }
            
            return null;
        }

        // 检查答案
        function checkAnswers() {
            let totalScore = 0;
            let answeredCount = 0;
            let totalQuestions = 0;
            
            // 检查单选题
            if (examData.singleChoice && examData.singleChoice.questions) {
                const singleChoiceResults = checkSingleChoiceAnswers();
                totalScore += singleChoiceResults.score;
                answeredCount += singleChoiceResults.answeredCount;
                totalQuestions += examData.singleChoice.questions.length;
            }
            
            // 检查多选题
            if (examData.multipleChoice && examData.multipleChoice.questions) {
                const multipleChoiceResults = checkMultipleChoiceAnswers();
                totalScore += multipleChoiceResults.score;
                answeredCount += multipleChoiceResults.answeredCount;
                totalQuestions += examData.multipleChoice.questions.length;
            }
            
            // 检查判断题
            if (examData.judge && examData.judge.questions) {
                const judgeResults = checkJudgeAnswers();
                totalScore += judgeResults.score;
                answeredCount += judgeResults.answeredCount;
                totalQuestions += examData.judge.questions.length;
            }
            
            // 更新总分显示
            totalScoreValue.textContent = totalScore;
            
            return {
                totalScore: totalScore,
                answeredCount: answeredCount,
                totalQuestions: totalQuestions
            };
        }


        // 检查单选题答案
        function checkSingleChoiceAnswers() {
            let score = 0;
            let answeredCount = 0;
            
            examData.singleChoice.questions.forEach(question => {
                const questionDiv = document.querySelector(`.question[data-id="${question.id}"][data-type="single"]`);
                const selectedOption = document.querySelector(`input[name="single_${question.id}"]:checked`);
                
                let userAnswer = selectedOption ? selectedOption.value : '';
                let isCorrect = userAnswer === question.answer;
                
                // 获取题目分数
                // 优先使用题目自定义分数，否则使用从标题解析的分数
                const questionScore = question.score !== undefined 
                    ? question.score 
                    : parseInt(questionDiv.dataset.score) || 0;
                
                if (userAnswer) answeredCount++;
                
                if (isCorrect) {
                    score += questionScore;
                    questionDiv.classList.add('correct');
                } else if (userAnswer) {
                    questionDiv.classList.add('incorrect');
                }
            });
            
            return {
                score: score,
                answeredCount: answeredCount
            };
        }

        // 检查多选题答案
        function checkMultipleChoiceAnswers() {
            let score = 0;
            let answeredCount = 0;
            
            examData.multipleChoice.questions.forEach(question => {
                const questionDiv = document.querySelector(`.question[data-id="${question.id}"][data-type="multiple"]`);
                const selectedOptions = document.querySelectorAll(`input[name="multiple_${question.id}"]:checked`);
                
                // 获取用户选择的答案
                const userAnswer = Array.from(selectedOptions).map(opt => opt.value);
                
                // 获取正确答案
                const correctAnswer = question.answer.split('');
                
                // 获取题目分数
                const questionScore = question.score !== undefined 
                    ? question.score 
                    : parseInt(questionDiv.dataset.score) || 0;
                
                // 检查是否有回答
                if (userAnswer.length > 0) {
                    answeredCount++;
                    
                    // 检查是否完全正确
                    const isCorrect = userAnswer.length === correctAnswer.length && 
                                     userAnswer.every(option => correctAnswer.includes(option));
                    
                    if (isCorrect) {
                        score += questionScore;
                        questionDiv.classList.add('correct');
                    } else {
                        questionDiv.classList.add('incorrect');
                    }
                }
            });
            
            return {
                score: score,
                answeredCount: answeredCount
            };
        }

        // 检查判断题答案
        function checkJudgeAnswers() {
            let score = 0;
            let answeredCount = 0;
            
            examData.judge.questions.forEach(question => {
                const questionDiv = document.querySelector(`.question[data-id="${question.id}"][data-type="judge"]`);
                const selectedOption = document.querySelector(`input[name="judge_${question.id}"]:checked`);
                
                let userAnswer = selectedOption ? selectedOption.value : '';
                let isCorrect = userAnswer === question.answer;
                
                // 获取题目分数
                const questionScore = question.score !== undefined 
                    ? question.score 
                    : parseInt(questionDiv.dataset.score) || 0;
                
                if (userAnswer) answeredCount++;
                
                if (isCorrect) {
                    score += questionScore;
                    questionDiv.classList.add('correct');
                } else if (userAnswer) {
                    questionDiv.classList.add('incorrect');
                }
            });
            
            return {
                score: score,
                answeredCount: answeredCount
            };
        }
        // 打印功能
        printBtn.addEventListener('click', function() {
            // 检查姓名和电话是否填写
            if (!studentName.value.trim()) {
                showModal('提示', '请填写您的姓名', () => {});
                return;
            }
            
            if (!studentPhone.value.trim()) {
                showModal('提示', '请填写您的电话号码', () => {});
                return;
            }
            
            // 更新水印内容
            updateWatermark();
            
            // 延迟打印以确保DOM更新完成
            setTimeout(() => {
                window.print();
            }, 100);
        });

        // 更新水印内容
        function updateWatermark() {
            const name = studentName.value.trim();
            const phone = studentPhone.value.trim();
            
            if (name && phone) {
                watermark.textContent = `${name} ${phone}`;
            }
        }

        // 提交并批改
        checkBtn.addEventListener('click', function() {
            // 新增：显示密码输入模态框
            showPasswordModal(function(password) {
                // 验证密码
                if (md5(password) === examPassword) {
                    showModal('确认提交', '确定要提交答案吗？提交后将不能修改。', function() {
                        // 记录交卷时间
                        submitTime = new Date();
                        updateSubmitTimeDisplay();

                        const result = checkAnswers();
                        isSubmitted = true;
                        
                        // 禁用所有输入
                        document.querySelectorAll('input[type="radio"], input[type="checkbox"]').forEach(input => {
                            input.disabled = true;
                        });
                        
                        // 更改按钮状态
                        checkBtn.disabled = true;
                        checkBtn.innerHTML = '<i class="fas fa-check-circle"></i> 已提交';
                        checkBtn.style.backgroundColor = '#95a5a6';
                        
                        // 显示总分
                        totalScoreDisplay.style.display = 'block';
                        
                        // 添加总分计算动画
                        animateScore(result.totalScore);
                    });
                } else {
                    showModal('密码错误', '您输入的密码不正确，请重试。', () => {});
                }
            });
        });

        // 交卷时间显示
        function updateSubmitTimeDisplay() {
            const submitTimeElement = document.getElementById('submitTime');
            submitTimeElement.textContent = `${formatDateTime(submitTime)}`;
        }

        // 重置答案
        resetBtn.addEventListener('click', function() {
            if (isSubmitted) {
                showModal('操作失败', '考试已提交，不能重置答案。', () => {});
                return;
            }
            
            showModal('确认重置', '确定要重置所有答案吗？', function() {
                resetAnswers();
                totalScoreValue.textContent = '0';
                totalScoreDisplay.style.display = 'none';
            });
        });

        // 检查答案
        function checkAnswers() {
            let totalScore = 0;
            let answeredCount = 0;
            let totalQuestions = 0;
            
            // 检查单选题
            if (examData.singleChoice && examData.singleChoice.questions) {
                const singleChoiceResults = checkSingleChoiceAnswers();
                totalScore += singleChoiceResults.score;
                answeredCount += singleChoiceResults.answeredCount;
                totalQuestions += examData.singleChoice.questions.length;
            }
            
            // 检查多选题
            if (examData.multipleChoice && examData.multipleChoice.questions) {
                const multipleChoiceResults = checkMultipleChoiceAnswers();
                totalScore += multipleChoiceResults.score;
                answeredCount += multipleChoiceResults.answeredCount;
                totalQuestions += examData.multipleChoice.questions.length;
            }
            
            // 检查判断题
            if (examData.judge && examData.judge.questions) {
                const judgeResults = checkJudgeAnswers();
                totalScore += judgeResults.score;
                answeredCount += judgeResults.answeredCount;
                totalQuestions += examData.judge.questions.length;
            }
            
            // 更新总分显示
            totalScoreValue.textContent = totalScore;
            
            return {
                totalScore: totalScore,
                answeredCount: answeredCount,
                totalQuestions: totalQuestions
            };
        }

        // 重置答案
        function resetAnswers() {
            // 清除单选和多选
            document.querySelectorAll('input[type="radio"], input[type="checkbox"]').forEach(input => {
                input.checked = false;
                input.disabled = false;
            });
            
            // 清除样式
            document.querySelectorAll('.question').forEach(question => {
                question.classList.remove('correct', 'incorrect');
            });
            
            // 重置提交状态
            isSubmitted = false;
            checkBtn.disabled = false;
            checkBtn.innerHTML = '<i class="fas fa-check-circle"></i> 提交并批改';
            checkBtn.style.backgroundColor = '';
        }
        
         // 分数动画效果
        function animateScore(finalScore) {
            let currentScore = 0;
            const duration = 1500; // 动画持续时间，单位毫秒
            const frameRate = 1000 / 60; // 每帧持续时间，60fps
            const totalFrames = Math.round(duration / frameRate);
            const increment = finalScore / totalFrames;
            
            const timer = setInterval(() => {
                currentScore += increment;
                if (currentScore >= finalScore) {
                    currentScore = finalScore;
                    clearInterval(timer);
                }
                totalScoreValue.textContent = Math.round(currentScore);
            }, frameRate);
        }
        
        // 显示密码输入模态框
        function showPasswordModal(callback) {
            // 创建密码输入表单
            const passwordForm = document.createElement('div');
            passwordForm.innerHTML = `
                <input type="password" id="passwordInput" class="password-input" placeholder="请输入提交密码">
                <div id="passwordError" class="password-error">密码不能为空</div>
            `;
            
            // 显示模态框
            modalTitle.textContent = '输入密码';
            modalContent.innerHTML = '';
            modalContent.appendChild(passwordForm);
            currentModalCallback = callback;
            
            // 显示模态框
            modal.classList.add('active');
            
            // 阻止背景滚动
            document.body.style.overflow = 'hidden';
            
            // 聚焦到密码输入框
            const passwordInput = document.getElementById('passwordInput');
            const passwordError = document.getElementById('passwordError');
            
            passwordInput.focus();
            
            // 隐藏错误信息
            passwordError.style.display = 'none';
            
            // 验证密码输入
            modalConfirm.onclick = function() {
                const password = passwordInput.value.trim();
                
                if (!password) {
                    passwordError.style.display = 'block';
                    return;
                }
                
                hideModal();
                if (typeof callback === 'function') {
                    callback(password);
                }
            };
            
            // 按回车键提交密码
            passwordInput.onkeypress = function(e) {
                if (e.key === 'Enter') {
                    modalConfirm.click();
                }
            };
        }
        
        // 显示模态框
        function showModal(title, content, confirmCallback) {
            modalTitle.textContent = title;
            modalContent.textContent = content;
            currentModalCallback = confirmCallback;
            
            // 显示模态框
            modal.classList.add('active');
            
            // 阻止背景滚动
            document.body.style.overflow = 'hidden';
            
            // 重置模态框确认按钮事件
            modalConfirm.onclick = function() {
                if (typeof currentModalCallback === 'function') {
                    currentModalCallback();
                }
                hideModal();
            };
        }
        
        // 隐藏模态框
        function hideModal() {
            modal.classList.remove('active');
            document.body.style.overflow = '';
            currentModalCallback = null;
        }
        
        // 模态框事件监听
        modalClose.addEventListener('click', hideModal);
        modalCancel.addEventListener('click', hideModal);
        modal.addEventListener('click', function(e) {
            if (e.target === modal) {
                hideModal();
            }
        });
        
        // MD5实现
        function md5(string) {
            function RotateLeft(lValue, iShiftBits) {
                return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits));
            }
            
            function AddUnsigned(lX, lY) {
                var lX4, lY4, lX8, lY8, lResult;
                lX8 = (lX & 0x80000000);
                lY8 = (lY & 0x80000000);
                lX4 = (lX & 0x40000000);
                lY4 = (lY & 0x40000000);
                lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF);
                if (lX4 & lY4) {
                    return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
                }
                if (lX4 | lY4) {
                    if (lResult & 0x40000000) {
                        return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
                    } else {
                        return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
                    }
                } else {
                    return (lResult ^ lX8 ^ lY8);
                }
            }
            
            function F(x, y, z) {
                return (x & y) | ((~x) & z);
            }
            
            function G(x, y, z) {
                return (x & z) | (y & (~z));
            }
            
            function H(x, y, z) {
                return x ^ y ^ z;
            }
            
            function I(x, y, z) {
                return y ^ (x | (~z));
            }
            
            function FF(a, b, c, d, x, s, ac) {
                a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
                return AddUnsigned(RotateLeft(a, s), b);
            }
            
            function GG(a, b, c, d, x, s, ac) {
                a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
                return AddUnsigned(RotateLeft(a, s), b);
            }
            
            function HH(a, b, c, d, x, s, ac) {
                a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
                return AddUnsigned(RotateLeft(a, s), b);
            }
            
            function II(a, b, c, d, x, s, ac) {
                a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
                return AddUnsigned(RotateLeft(a, s), b);
            }
            
            function ConvertToWordArray(string) {
                var lWordCount;
                var lMessageLength = string.length;
                var lNumberOfWords_temp1 = lMessageLength + 8;
                var lNumberOfWords_temp2 = (lNumberOfWords_temp1 - (lNumberOfWords_temp1 % 64)) / 64;
                var lNumberOfWords = (lNumberOfWords_temp2 + 1) * 16;
                var lWordArray = Array(lNumberOfWords - 1);
                var lBytePosition = 0;
                var lByteCount = 0;
                while (lByteCount < lMessageLength) {
                    lWordCount = (lByteCount - (lByteCount % 4)) / 4;
                    lBytePosition = (lByteCount % 4) * 8;
                    lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount) << lBytePosition));
                    lByteCount++;
                }
                lWordCount = (lByteCount - (lByteCount % 4)) / 4;
                lBytePosition = (lByteCount % 4) * 8;
                lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition);
                lWordArray[lNumberOfWords - 2] = lMessageLength << 3;
                lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29;
                return lWordArray;
            }
            
            function WordToHex(lValue) {
                var WordToHexValue = "",
                    WordToHexValue_temp = "",
                    lByte, lCount;
                for (lCount = 0; lCount <= 3; lCount++) {
                    lByte = (lValue >>> (lCount * 8)) & 255;
                    WordToHexValue_temp = "0" + lByte.toString(16);
                    WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length - 2, 2);
                }
                return WordToHexValue;
            }
            
            function Utf8Encode(string) {
                string = string.replace(/\r\n/g, "\n");
                var utftext = "";
                
                for (var n = 0; n < string.length; n++) {
                    var c = string.charCodeAt(n);
                    
                    if (c < 128) {
                        utftext += String.fromCharCode(c);
                    } else if ((c > 127) && (c < 2048)) {
                        utftext += String.fromCharCode((c >> 6) | 192);
                        utftext += String.fromCharCode((c & 63) | 128);
                    } else {
                        utftext += String.fromCharCode((c >> 12) | 224);
                        utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                        utftext += String.fromCharCode((c & 63) | 128);
                    }
                }
                return utftext;
            }
            
            var x = Array();
            var k, AA, BB, CC, DD, a, b, c, d;
            var S11 = 7,
                S12 = 12,
                S13 = 17,
                S14 = 22;
            var S21 = 5,
                S22 = 9,
                S23 = 14,
                S24 = 20;
            var S31 = 4,
                S32 = 11,
                S33 = 16,
                S34 = 23;
            var S41 = 6,
                S42 = 10,
                S43 = 15,
                S44 = 21;
            
            string = Utf8Encode(string);
            
            x = ConvertToWordArray(string);
            
            a = 0x67452301;
            b = 0xEFCDAB89;
            c = 0x98BADCFE;
            d = 0x10325476;
            
            for (k = 0; k < x.length; k += 16) {
                AA = a;
                BB = b;
                CC = c;
                DD = d;
                
                a = FF(a, b, c, d, x[k + 0], S11, 0xD76AA478);
                d = FF(d, a, b, c, x[k + 1], S12, 0xE8C7B756);
                c = FF(c, d, a, b, x[k + 2], S13, 0x242070DB);
                b = FF(b, c, d, a, x[k + 3], S14, 0xC1BDCEEE);
                a = FF(a, b, c, d, x[k + 4], S11, 0xF57C0FAF);
                d = FF(d, a, b, c, x[k + 5], S12, 0x4787C62A);
                c = FF(c, d, a, b, x[k + 6], S13, 0xA8304613);
                b = FF(b, c, d, a, x[k + 7], S14, 0xFD469501);
                a = FF(a, b, c, d, x[k + 8], S11, 0x698098D8);
                d = FF(d, a, b, c, x[k + 9], S12, 0x8B44F7AF);
                c = FF(c, d, a, b, x[k + 10], S13, 0xFFFF5BB1);
                b = FF(b, c, d, a, x[k + 11], S14, 0x895CD7BE);
                a = FF(a, b, c, d, x[k + 12], S11, 0x6B901122);
                d = FF(d, a, b, c, x[k + 13], S12, 0xFD987193);
                c = FF(c, d, a, b, x[k + 14], S13, 0xA679438E);
                b = FF(b, c, d, a, x[k + 15], S14, 0x49B40821);
                
                a = GG(a, b, c, d, x[k + 1], S21, 0xF61E2562);
                d = GG(d, a, b, c, x[k + 6], S22, 0xC040B340);
                c = GG(c, d, a, b, x[k + 11], S23, 0x265E5A51);
                b = GG(b, c, d, a, x[k + 0], S24, 0xE9B6C7AA);
                a = GG(a, b, c, d, x[k + 5], S21, 0xD62F105D);
                d = GG(d, a, b, c, x[k + 10], S22, 0x2441453);
                c = GG(c, d, a, b, x[k + 15], S23, 0xD8A1E681);
                b = GG(b, c, d, a, x[k + 4], S24, 0xE7D3FBC8);
                a = GG(a, b, c, d, x[k + 9], S21, 0x21E1CDE6);
                d = GG(d, a, b, c, x[k + 14], S22, 0xC33707D6);
                c = GG(c, d, a, b, x[k + 3], S23, 0xF4D50D87);
                b = GG(b, c, d, a, x[k + 8], S24, 0x455A14ED);
                a = GG(a, b, c, d, x[k + 13], S21, 0xA9E3E905);
                d = GG(d, a, b, c, x[k + 2], S22, 0xFCEFA3F8);
                c = GG(c, d, a, b, x[k + 7], S23, 0x676F02D9);
                b = GG(b, c, d, a, x[k + 12], S24, 0x8D2A4C8A);
                
                a = HH(a, b, c, d, x[k + 5], S31, 0xFFFA3942);
                d = HH(d, a, b, c, x[k + 8], S32, 0x8771F681);
                c = HH(c, d, a, b, x[k + 11], S33, 0x6D9D6122);
                b = HH(b, c, d, a, x[k + 14], S34, 0xFDE5380C);
                a = HH(a, b, c, d, x[k + 1], S31, 0xA4BEEA44);
                d = HH(d, a, b, c, x[k + 4], S32, 0x4BDECFA9);
                c = HH(c, d, a, b, x[k + 7], S33, 0xF6BB4B60);
                b = HH(b, c, d, a, x[k + 10], S34, 0xBEBFBC70);
                a = HH(a, b, c, d, x[k + 13], S31, 0x289B7EC6);
                d = HH(d, a, b, c, x[k + 0], S32, 0xEAA127FA);
                c = HH(c, d, a, b, x[k + 3], S33, 0xD4EF3085);
                b = HH(b, c, d, a, x[k + 6], S34, 0x4881D05);
                a = HH(a, b, c, d, x[k + 9], S31, 0xD9D4D039);
                d = HH(d, a, b, c, x[k + 12], S32, 0xE6DB99E5);
                c = HH(c, d, a, b, x[k + 15], S33, 0x1FA27CF8);
                b = HH(b, c, d, a, x[k + 2], S34, 0xC4AC5665);
                
                a = II(a, b, c, d, x[k + 0], S41, 0xF4292244);
                d = II(d, a, b, c, x[k + 7], S42, 0x432AFF97);
                c = II(c, d, a, b, x[k + 14], S43, 0xAB9423A7);
                b = II(b, c, d, a, x[k + 5], S44, 0xFC93A039);
                a = II(a, b, c, d, x[k + 12], S41, 0x655B59C3);
                d = II(d, a, b, c, x[k + 3], S42, 0x8F0CCC92);
                c = II(c, d, a, b, x[k + 10], S43, 0xFFEFF47D);
                b = II(b, c, d, a, x[k + 1], S44, 0x85845DD1);
                a = II(a, b, c, d, x[k + 8], S41, 0x6FA87E4F);
                d = II(d, a, b, c, x[k + 15], S42, 0xFE2CE6E0);
                c = II(c, d, a, b, x[k + 6], S43, 0xA3014314);
                b = II(b, c, d, a, x[k + 13], S44, 0x4E0811A1);
                a = II(a, b, c, d, x[k + 4], S41, 0xF7537E82);
                d = II(d, a, b, c, x[k + 11], S42, 0xBD3AF235);
                c = II(c, d, a, b, x[k + 2], S43, 0x2AD7D2BB);
                b = II(b, c, d, a, x[k + 9], S44, 0xEB86D391);
                
                a = AddUnsigned(a, AA);
                b = AddUnsigned(b, BB);
                c = AddUnsigned(c, CC);
                d = AddUnsigned(d, DD);
            }
            
            var temp = WordToHex(a) + WordToHex(b) + WordToHex(c) + WordToHex(d);
            
            return temp.toLowerCase();
        }

        // 日期格式化函数
        function formatDateTime(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            
            return `${year}年${month}月${day}日 ${hours}时${minutes}分${seconds}秒`;
        }
    </script>
</body>
</html>